﻿namespace NuGetCop.MSBuild.Tasks
{
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using NuGetCop.MSBuild.Tasks.Resources;

    internal sealed class NuGetPackageCheckResultAggregator : INuGetPackageCheckResultAggregator
    {
        public INuGetPackageCheckResult Aggregate(
            ICollection<INuGetPackageCheckResult> checkResults,
            INuGetPackageRepository packageRepository)
        {
            var packageReferencesCache = new HashSet<INuGetPackageReference>(
                packageRepository.PackageReferences);

            var errors = new List<string>();

            foreach (var checkResult in checkResults)
            {
                if (checkResult == null)
                {
                    continue;
                }

                foreach (var packageRef in checkResult.RelatedPackages)
                {
                    packageReferencesCache.Remove(packageRef);
                }

                errors.AddRange(checkResult.Errors);
            }

            errors.AddRange(packageReferencesCache
                .Select(packageRef => 
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Msg.UnknownPackageReferenceFormat, 
                        packageRef.Id, 
                        packageRef.Version, 
                        packageRef.TargetFramework)));

            var aggregatedResult = new NuGetPackageCheckResult(
                packageRepository.PackageReferences, 
                errors);

            return aggregatedResult;
        }
    }
}